import 'package:flutter/material.dart';
import 'package:gd_assistant/page/public/colors.dart';
import 'package:gd_assistant/page/public/publicView.dart';
import 'package:gd_assistant/page/public/publicTool.dart';
import 'package:gd_assistant/page/public/themeUtils.dart';
import 'package:gd_assistant/third/flutter_datetime_picker.dart';
import 'package:gd_assistant/model/patientModel.dart';
import 'package:gd_assistant/api/apiHandler.dart';
import 'package:gd_assistant/util/RelativeDateFormat.dart';

class patientInfoPage extends StatefulWidget {
  patientInfoPage({Key key,this.userId, this.orderId, this.isNew = false, this.callBack}):super(key: key);
  String userId;
  String orderId;
  Function callBack;
  bool isNew;
  @override
  _patientInfoPageState createState() => _patientInfoPageState();
}

class _patientInfoPageState extends State<patientInfoPage> {
  bool isDark = false;
  String patientInfoId = "";
  String userId = "";
  String orderId = "";
  TextEditingController name = TextEditingController();
  var sex = "";
  TextEditingController phone = TextEditingController();
  var born = "";
  TextEditingController seeNum = TextEditingController();
  var menstruationDay = "";
  var preDay = "";
  var proDay = "";
  var area = "";
  TextEditingController allergy = TextEditingController(); 
  TextEditingController desc = TextEditingController();
  TextEditingController address = TextEditingController();
  bool isLoad = false;

  String costType = "";

  final bottomTitles = ["男","女"];
  final costTypeTitles = ["自费","生育保险","省公医","市公医","区公医","其他"];
  final areaTitles = ["天河区","海珠区","白云区","荔湾区","越秀区","黄埔区","番禺区","南沙区","花都区","从化区","增城区","其他"];

  _bottomTap(title) {
    setState(() {
      sex = title;
    });
  }

  _areaTap(title) {
    setState(() {
      area = title;
    });
  }

  _bottomCostTypeTap(title) {
    setState(() {
      costType = title;
    });
  }

  @override
  void initState() {
    super.initState();
    if (widget.userId != null) {
      userId = widget.userId;
    }
    if (widget.orderId != null && widget.isNew == false) {
      orderId = widget.orderId;
      loadData();
    }
    name.addListener(() { setState(() {}); });
    phone.addListener(() { setState(() {}); });
  }

  void loadData() async {
      isLoad = true;
      PatientModel patient = await apiHandler.getMemberDetail(userId, orderId);
      isLoad = false;
      patientInfoId = patient.patientInfoId;
      name.text = patient.name;
      sex = patient.sex;
      phone.text = patient.phoneNum;
      born = patient.birth != null ? RelativeDateFormat.YMDformat(patient.birth) : "";
      seeNum.text = patient.medicalNumber;
      preDay = patient.expectedDate != null ? RelativeDateFormat.YMDformat(patient.expectedDate) : "";
      menstruationDay = patient.lastMenstruation != null ? RelativeDateFormat.YMDformat(patient.lastMenstruation) : "";
      proDay = patient.babyBirth != null ? RelativeDateFormat.YMDformat(patient.babyBirth) : "";
      allergy.text = patient.allergyHistory;
      desc.text = patient.note;
      costType = patient.costType;
      area = patient.area;
      address.text = patient.address;
      //设置延迟显示
      Future.delayed(Duration(milliseconds: 300), (){
         setState(() {});    
      });
  }

  void updatePatientInfo() async {
    TostUtil.showLoading(context, "就诊人信息提交中...");
    dynamic cb;
    if (widget.isNew) {
      cb = await apiHandler.createCommonPatient(name.text, RelativeDateFormat.timeStampFormat(born), sex, seeNum.text,  RelativeDateFormat.timeStampFormat(menstruationDay), phone.text, RelativeDateFormat.timeStampFormat(preDay), userId, RelativeDateFormat.timeStampFormat(proDay), desc.text, allergy.text, costType, area, address.text);
    }else {
      print(area);
      cb = await apiHandler.updatePatientInfo(patientInfoId, name.text, phone.text, RelativeDateFormat.timeStampFormat(born), sex, seeNum.text, RelativeDateFormat.timeStampFormat(menstruationDay), RelativeDateFormat.timeStampFormat(preDay), RelativeDateFormat.timeStampFormat(proDay), allergy.text, desc.text, costType, area, address.text);
    }
    
    TostUtil.removeLoading(context);

    if (cb != null) {
      TostUtil.show("档案提交成功");
      Navigator.pop(context);
    }
    
    if (widget.callBack != null) {
      if (widget.isNew) {
        PatientModel pt = cb;
        pt.isNewPatient = "1";
        widget.callBack(pt);
      }else {
        widget.callBack(name.text);
      }
    }
  }

  _getBodyWidget() {
    if (isLoad) {
      return loadingWiget();
    }
    final EdgeInsets padding = MediaQuery.of(context).padding;
    return Container(
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: ListView(
                children: <Widget>[
                  ZLTextField(
                    title: "姓名",
                    controller: name,
                    pliceHorder: "请输入名字",
                  ),
                  ZLSelectField(
                    title: "性别",
                    text: sex,
                    pliceHorder: "请选择性别",
                    onTap: () {
                      publicTool.showBottomSheet(context, bottomTitles, _bottomTap);
                    },
                  ),
                  ZLTextField(
                    title: "手机号",
                    controller: phone,
                    pliceHorder: "请输入手机号",
                    inputType: TextInputType.number,
                  ),
                  ZLSelectField(
                    title: "出生日期",
                    text: born,
                    pliceHorder: "请选择出生日期",
                    onTap: () {
                        DatePicker.showDatePicker(context,
                            showTitleActions: true,
                            minTime: DateTime(1900),
                            onConfirm: (date) {
                            setState(() {
                              born = RelativeDateFormat.YMDformat(date.millisecondsSinceEpoch);
                            });
                        }, locale: LocaleType.zh);
                    },
                  ),
                  ZLSelectField(
                    title: "所属区域",
                    text:  area,
                    pliceHorder: "请选择所属区域",
                    onTap: () {
                      publicTool.showBottomSheet(context, areaTitles, _areaTap);
                    },
                  ),
                  ZLSelectField(
                    title: "费用类型",
                    text:  costType,
                    pliceHorder: "请选择费用类型",
                    onTap: () {
                      publicTool.showBottomSheet(context, costTypeTitles, _bottomCostTypeTap);
                    },
                  ),
                  ZLTextField(
                    title: "就诊卡号",
                    controller: seeNum,
                    pliceHorder: "请输入就诊卡号",
                    inputType: TextInputType.number,
                  ),
                  ZLSelectField(
                    title: "末次月经",
                    text: menstruationDay,
                    pliceHorder: "请选择末次月经日期",
                    onTap: () {
                      DatePicker.showDatePicker(context,
                            showTitleActions: true,
                            minTime: DateTime(1900),
                            onConfirm: (date) {
                            setState(() {
                              menstruationDay = RelativeDateFormat.YMDformat(date.millisecondsSinceEpoch);
                            });
                        }, locale: LocaleType.zh);
                    },
                  ),
                  ZLSelectField(
                    title: "预产期",
                    text: preDay,
                    pliceHorder: "请选择预产日期",
                    onTap: (){
                      DatePicker.showDatePicker(context,
                            showTitleActions: true,
                            onConfirm: (date) {
                            setState(() {
                              preDay = RelativeDateFormat.YMDformat(date.millisecondsSinceEpoch);
                            });
                        }, locale: LocaleType.zh);
                    },
                  ),
                  ZLSelectField(
                    title: "生产日期",
                    text: proDay,
                    pliceHorder: "请产科会员生产后选择",
                    onTap: () {
                      DatePicker.showDatePicker(context,
                            showTitleActions: true,
                            onConfirm: (date) {
                            setState(() {
                              proDay = RelativeDateFormat.YMDformat(date.millisecondsSinceEpoch);
                            });
                        }, locale: LocaleType.zh);
                    },
                  ),
                  ZLTextView(
                    title: "过敏史",
                    controller: allergy,
                    pliceHorder: "请输入过敏史",
                  ),
                  ZLTextView(
                    title: "备注",
                    controller: desc,
                    pliceHorder: "请输入备注",
                  ),
                  ZLTextView(
                    title: "收件地址",
                    controller: address,
                    pliceHorder: "请输入收件地址",
                  ),
                ],
              ),
            ),
           Container(
              padding: EdgeInsets.only(bottom: padding.bottom),
              width: double.infinity,
              height: 65 + padding.bottom,
              color: isDark ? Colours.dark_bg_color : Colors.white,
              child: ZLButton(
                  title: "完成",
                  onTap: name.text != "" && sex != "" && phone.text != "" && born != "" && area != ""? (){
                    updatePatientInfo();
                  } : null
                )
            ),
          ],
        )
      );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    name.dispose();
    phone.dispose();
    seeNum.dispose();
    allergy.dispose(); 
    desc.dispose();
  }

  @override
  Widget build(BuildContext context) {
    isDark = ThemeUtils.isDark(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("就诊人信息"),
        elevation: 0
      ),
      body: _getBodyWidget()
    );
  }
}